<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>爪印</h2>
        <p>宠物领养平台</p>
      </div>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        label-width="0"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            type="password"
            prefix-icon="el-icon-lock"
            show-password
            @keyup.enter="handleLogin"
          ></el-input>
        </el-form-item>

        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter="handleLogin"
          >
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>

        <el-form-item>
          <div class="form-options">
            <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="el-login-footer">
      <span>爪印宠物领养平台 © 2024 版权所有</span>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { getCodeImg } from "@/api/user";
import Cookies from "js-cookie";

const router = useRouter();
const route = useRoute();
const store = useStore();
const loginFormRef = ref(null);
const loading = ref(false);

// 验证码开关
const captchaEnabled = ref(true);
const codeUrl = ref("");

const loginForm = reactive({
  username: "",
  password: "",
  remember: false,
  code: "",
  uuid: "",
});

const loginRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6个字符", trigger: "blur" },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;

      // 记住我功能
      if (loginForm.remember) {
        Cookies.set("username", loginForm.username, { expires: 30 });
        Cookies.set("remember", loginForm.remember, { expires: 30 });
      } else {
        Cookies.remove("username");
        Cookies.remove("remember");
      }

      // 调用store的登录方法
      store
        .dispatch("Login", loginForm)
        .then(() => {
          // 登录成功后，获取用户信息
          return store.dispatch("GetInfo");
        })
        .then(() => {
          loading.value = false;
          ElMessage.success("登录成功");

          // 成功登录后跳转
          const redirectUrl = route.query.redirect || "/";
          router.push(redirectUrl);
        })
        .catch((error) => {
          console.error("登录失败:", error);
          loading.value = false;

          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }

          // 登录失败时降级使用模拟登录
          handleMockLogin();
        });
    }
  });
};

// 获取验证码
function getCode() {
  getCodeImg()
    .then((res) => {
      captchaEnabled.value =
        res.captchaEnabled === undefined ? true : res.captchaEnabled;
      if (captchaEnabled.value) {
        codeUrl.value = "data:image/gif;base64," + res.img;
        loginForm.uuid = res.uuid;
      }
    })
    .catch(() => {
      captchaEnabled.value = false;
    });
}

// 从Cookie中获取用户信息
function getCookie() {
  const username = Cookies.get("username");
  const remember = Cookies.get("remember");

  if (username) {
    loginForm.username = username;
  }
  if (remember) {
    loginForm.remember = remember === "true";
  }
}

// 模拟登录方法（用于后端API不可用时的降级处理）
const handleMockLogin = () => {
  // 存储本地登录状态
  localStorage.setItem("isLogin", "true");
  localStorage.setItem("username", loginForm.username);
  // 添加模拟的用户ID
  localStorage.setItem("userId", "1"); // 使用默认用户ID为1
  ElMessage.warning("后端服务不可用，使用模拟登录");

  // 成功登录后跳转
  const redirectUrl = route.query.redirect || "/";
  router.push(redirectUrl);
};

// 页面加载时获取验证码和Cookie
getCode();
getCookie();
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-size: cover;
  background-position: center;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.login-header p {
  color: #909399;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-button {
  width: 100%;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;
}

.login-code-img {
  height: 40px;
  cursor: pointer;
  vertical-align: middle;
  padding-left: 10px;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #666;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
